<template>
  <el-dialog
    v-model="visible"
    :title="!dataForm.stockChangeReasonId ? $t('crud.addTitle') : $t('crud.updateBtn')"
    :close-on-click-modal="false"
    class="component-customizereason-add-or-update"
  >
    <!-- native modifier has been removed, please confirm whether the function has been affected  -->
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      :rules="dataRule"
      label-width="150px"
      @keyup.enter="onSubmit()"
    >
      <!-- 出入库类别 -->
      <el-form-item
        :label="$t('stock.stockType')"
        prop="type"
      >
        <el-radio
          v-model="dataForm.type"
          :label="1"
          :value="1"
        >
          {{ $t('stock.sendStock') }}
        </el-radio>
        <el-radio
          v-model="dataForm.type"
          :label="2"
          :value="2"
        >
          {{ $t('stock.receiveStock') }}
        </el-radio>
      </el-form-item>
      <!-- 语言选择 -->
      <el-form-item
        v-if="langItemList.length > 1"
        :label="$t('product.chooseLanguage')"
      >
        <el-select
          v-model="curLang"
          multiple
          :placeholder="$t('tip.select')"
          style="width: 100%;"
          @change="selectLang"
        >
          <el-option
            v-for="item in langItemList"
            :key="item.lang"
            :label="item.name"
            :value="item.lang"
          />
        </el-select>
      </el-form-item>
      <!-- 出入库原因 -->
      <div
        v-for="(item,index) in stockChangeReasonLangList"
        :key="index"
      >
        <el-form-item :label="$t('stock.stockBillReason') + (langItemList.length === 1 ? '' : `(${item.langName})`)">
          <el-input
            v-model="item.reason"
            maxlength="10"
            type="text"
          />
        </el-form-item>
      </div>

      <!-- 备注 -->

      <div
        v-for="(item,index) in stockChangeReasonLangList"
        :key="index"
      >
        <el-form-item :label="$t('stock.remark') + (langItemList.length === 1 ? '' : `(${item.langName})`)">
          <el-input
            v-model="item.remark"
            maxlength="10"
            type="text"
          />
        </el-form-item>
      </div>
    </el-form>
    <template #footer>
      <span
        class="dialog-footer"
      >
        <div
          class="default-btn"
          @click="visible = false"
        >{{ $t('order.cancel') }}</div>
        <div
          class="default-btn primary-btn"
          @click="onSubmit()"
        >{{ $t('order.confirm') }}</div>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from 'element-plus'
const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataForm = reactive({
  type: 1,
  reasonCn: null,
  reasonEn: null,
  status: null,
  remarkCn: null,
  remarkEn: null
})
// 语言列表
const langItemList = ref([])
const masterLangInfo = { name: '', lang: '' }
// 当前所选语言
const curLang = ref([])
const stockChangeReasonLangList = ref([])
const dataRule = {
  type: [
    { required: true, message: $t('stock.stockTypeNotEmpty'), trigger: 'blur' }
  ]
}

const dataFormRef = ref(null)
const init = (stockChangeReasonId, type) => {
  dataForm.stockChangeReasonId = stockChangeReasonId || 0
  dataForm.reasonCn = null
  dataForm.reasonEn = null
  dataForm.status = null
  dataForm.remarkCn = null
  dataForm.remarkEn = null
  visible.value = true
  stockChangeReasonLangList.value = []
  if (!stockChangeReasonId) {
    dataForm.type = type === 2 ? 2 : 1
    getLangList()
  } else {
    nextTick(() => {
      dataFormRef.value?.resetFields()
      if (dataForm.stockChangeReasonId) {
        http({
          url: http.adornUrl('/shop/stockChangeReason/info/' + dataForm.stockChangeReasonId),
          method: 'get',
          params: http.adornParams()
        }).then(({ data }) => {
          dataForm.type = data.type
          dataForm.status = data.status
          stockChangeReasonLangList.value = data.stockChangeReasonLangList
          getLangList()
        })
      } else {
        getLangList()
      }
    })
  }
}
defineExpose({ init })
const getLangList = () => {
  http({
    url: http.adornUrl('/sys/lang'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    if (data) {
      const info = data
      masterLangInfo.name = info.name
      masterLangInfo.lang = info.lang
      langItemList.value = info.langItemList
      // 设置默认主语言
      if (!stockChangeReasonLangList.value) {
        selectLang([info.lang])
      } else {
        // 初始化所选语言
        const curLang = []
        const _stockChangeReasonLangList = []
        for (const item of langItemList.value) {
          const fd = stockChangeReasonLangList.value.find(it => it.lang === item.lang)
          if (fd) {
            fd.langName = item.name
            _stockChangeReasonLangList.push(fd)
            curLang.push(item.lang)
          }
        }
        stockChangeReasonLangList.value = _stockChangeReasonLangList
        selectLang(curLang)
      }
    }
  })
}
/**
 * 选择语言(主语言信息必填)
 */
const selectLang = (value) => {
  curLang.value = value
  // 设置主语言不可删除
  if (!curLang.value.includes(masterLangInfo.lang)) {
    curLang.value.unshift(masterLangInfo.lang)
  }
  // 所选语言改变
  const tempArr = stockChangeReasonLangList.value.filter(item => curLang.value.includes(item.lang))

  curLang.value.forEach((item, index) => {
    if (!tempArr.find(f => f.lang == item)) {
      const fd = langItemList.value.find(it => it.lang === item)
      if (fd) {
        tempArr.splice(index, 0, { langName: fd.name, lang: item, stockChangeReasonId: dataForm.stockChangeReasonId, reason: '', remark: '' })
      }
    }
  })
  stockChangeReasonLangList.value = tempArr
}
// 表单提交
const onSubmit = () => {
  dataFormRef.value?.validate((valid) => {
    for (let i = 0; i < stockChangeReasonLangList.value.length; i++) {
      if (!stockChangeReasonLangList.value[i].reason || !stockChangeReasonLangList.value[i].reason.trim()) {
        ElMessage({
          message: $t('stock.stockBillReasonNotEmpty'),
          type: 'error',
          duration: 1500
        })
        return false
      }
    }
    dataForm.stockChangeReasonLangList = stockChangeReasonLangList.value
    if (valid) {
      http({
        url: http.adornUrl('/shop/stockChangeReason'),
        method: dataForm.stockChangeReasonId ? 'put' : 'post',
        data: http.adornData(dataForm)
      }).then(() => {
        ElMessage({
          message: $t('publics.operation'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            visible.value = false
            emit('refreshDataList')
          }
        })
      })
    }
  })
}

</script>
